package com.pond.pond.controller;

import com.alibaba.fastjson2.JSONObject;
import com.pond.common.core.domain.R;
import com.pond.common.core.web.controller.BaseController;
import com.pond.common.security.annotation.RequiresLogin;
import com.pond.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 通知消息控制器
 * 管理Redis中存储的用户通知消息
 */
@Slf4j
@RestController
@RequestMapping("/app/notifications")
public class NotificationController extends BaseController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 获取当前用户的所有通知消息
     */
    @RequiresLogin
    @GetMapping("/messages")
    public R<List<Map<String, Object>>> getMessages(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {
        try {
            Long userId = SecurityUtils.getUserId();
            String redisKey = "admin:unread:" + userId;
            
            // 获取所有消息
            List<String> messages = redisTemplate.opsForList().range(redisKey, 0, -1);
            List<Map<String, Object>> result = new ArrayList<>();
            
            if (messages != null && !messages.isEmpty()) {
                int start = (pageNum - 1) * pageSize;
                int end = Math.min(start + pageSize, messages.size());
                
                for (int i = start; i < end; i++) {
                    String messageStr = messages.get(i);
                    try {
                        // 清理字符串
                        String cleanedMsg = messageStr.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim();
                        
                        if (cleanedMsg.startsWith("{")) {
                            JSONObject messageObj = JSONObject.parseObject(cleanedMsg);
                            
                            // 添加索引用于后续操作
                            messageObj.put("index", i);
                            messageObj.put("messageId", "msg_" + userId + "_" + i);
                            
                            result.add(messageObj);
                        }
                    } catch (Exception e) {
                        log.warn("解析消息失败: {}", messageStr, e);
                    }
                }
            }
            
            return R.ok(result);
        } catch (Exception e) {
            log.error("获取通知消息失败", e);
            return R.fail("获取通知消息失败");
        }
    }

    /**
     * 获取未读消息数量
     */
    @RequiresLogin
    @GetMapping("/unread-count")
    public R<Integer> getUnreadCount() {
        try {
            Long userId = SecurityUtils.getUserId();
            String redisKey = "admin:unread:" + userId;
            
            List<String> messages = redisTemplate.opsForList().range(redisKey, 0, -1);
            int unreadCount = 0;
            
            if (messages != null) {
                for (String messageStr : messages) {
                    try {
                        String cleanedMsg = messageStr.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim();
                        if (cleanedMsg.startsWith("{")) {
                            JSONObject messageObj = JSONObject.parseObject(cleanedMsg);
                            if (!messageObj.getBooleanValue("read")) {
                                unreadCount++;
                            }
                        }
                    } catch (Exception e) {
                        log.warn("解析消息失败: {}", messageStr, e);
                    }
                }
            }
            
            return R.ok(unreadCount);
        } catch (Exception e) {
            log.error("获取未读消息数量失败", e);
            return R.fail("获取未读消息数量失败");
        }
    }

    /**
     * 标记消息为已读
     */
    @RequiresLogin
    @PostMapping("/mark-read")
    public R<String> markAsRead(@RequestBody Map<String, Object> request) {
        try {
            Long userId = SecurityUtils.getUserId();
            String messageId = (String) request.get("messageId");
            Integer index = (Integer) request.get("index");
            
            if (index == null) {
                return R.fail("消息索引不能为空");
            }
            
            String redisKey = "admin:unread:" + userId;
            List<String> messages = redisTemplate.opsForList().range(redisKey, 0, -1);
            
            if (messages != null && index < messages.size()) {
                String messageStr = messages.get(index);
                try {
                    String cleanedMsg = messageStr.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim();
                    JSONObject messageObj = JSONObject.parseObject(cleanedMsg);
                    messageObj.put("read", true);
                    
                    // 更新Redis中的消息
                    redisTemplate.opsForList().set(redisKey, index, messageObj.toString());
                    
                    log.info("消息标记为已读成功: userId={}, index={}", userId, index);
                    return R.ok("标记成功");
                } catch (Exception e) {
                    log.error("解析消息失败: {}", messageStr, e);
                    return R.fail("消息格式错误");
                }
            } else {
                return R.fail("消息不存在");
            }
        } catch (Exception e) {
            log.error("标记消息已读失败", e);
            return R.fail("标记失败");
        }
    }

    /**
     * 标记所有消息为已读
     */
    @RequiresLogin
    @PostMapping("/mark-all-read")
    public R<String> markAllAsRead() {
        try {
            Long userId = SecurityUtils.getUserId();
            String redisKey = "admin:unread:" + userId;
            
            List<String> messages = redisTemplate.opsForList().range(redisKey, 0, -1);
            if (messages != null && !messages.isEmpty()) {
                List<String> updatedMessages = new ArrayList<>();
                
                for (String messageStr : messages) {
                    try {
                        String cleanedMsg = messageStr.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim();
                        if (cleanedMsg.startsWith("{")) {
                            JSONObject messageObj = JSONObject.parseObject(cleanedMsg);
                            messageObj.put("read", true);
                            updatedMessages.add(messageObj.toString());
                        } else {
                            updatedMessages.add(messageStr);
                        }
                    } catch (Exception e) {
                        log.warn("解析消息失败: {}", messageStr, e);
                        updatedMessages.add(messageStr);
                    }
                }
                
                // 原子性更新Redis列表
                redisTemplate.delete(redisKey);
                if (!updatedMessages.isEmpty()) {
                    redisTemplate.opsForList().rightPushAll(redisKey, updatedMessages);
                }
                
                log.info("所有消息标记为已读成功: userId={}", userId);
                return R.ok("全部标记成功");
            }
            
            return R.ok("无消息需要标记");
        } catch (Exception e) {
            log.error("标记所有消息已读失败", e);
            return R.fail("标记失败");
        }
    }

    /**
     * 删除消息
     */
    @RequiresLogin
    @DeleteMapping("/delete")
    public R<String> deleteMessage(@RequestParam Integer index) {
        try {
            Long userId = SecurityUtils.getUserId();
            String redisKey = "admin:unread:" + userId;
            
            List<String> messages = redisTemplate.opsForList().range(redisKey, 0, -1);
            if (messages != null && index < messages.size()) {
                List<String> updatedMessages = new ArrayList<>();
                
                for (int i = 0; i < messages.size(); i++) {
                    if (i != index) {
                        updatedMessages.add(messages.get(i));
                    }
                }
                
                // 原子性更新Redis列表
                redisTemplate.delete(redisKey);
                if (!updatedMessages.isEmpty()) {
                    redisTemplate.opsForList().rightPushAll(redisKey, updatedMessages);
                }
                
                log.info("消息删除成功: userId={}, index={}", userId, index);
                return R.ok("删除成功");
            } else {
                return R.fail("消息不存在");
            }
        } catch (Exception e) {
            log.error("删除消息失败", e);
            return R.fail("删除失败");
        }
    }

    /**
     * 清空所有消息
     */
    @RequiresLogin
    @DeleteMapping("/clear-all")
    public R<String> clearAllMessages() {
        try {
            Long userId = SecurityUtils.getUserId();
            String redisKey = "admin:unread:" + userId;
            
            redisTemplate.delete(redisKey);
            
            log.info("清空所有消息成功: userId={}", userId);
            return R.ok("清空成功");
        } catch (Exception e) {
            log.error("清空所有消息失败", e);
            return R.fail("清空失败");
        }
    }

    /**
     * 发送通知消息（供内部调用）
     */
    @PostMapping("/send")
    public R<String> sendNotification(@RequestBody Map<String, Object> request) {
        try {
            String toUserId = (String) request.get("toUserId");
            String notificationType = (String) request.get("notificationType");
            String title = (String) request.get("title");
            String content = (String) request.get("content");
            String senderName = (String) request.get("senderName");
            String senderId = (String) request.get("senderId");
            String targetId = (String) request.get("targetId");
            String targetType = (String) request.get("targetType");
            String navigationPath = (String) request.get("navigationPath");
            Map<String, Object> navigationParams = (Map<String, Object>) request.get("navigationParams");
            
            // 构建通知消息
            JSONObject messageContent = new JSONObject();
            messageContent.put("notificationType", notificationType);
            messageContent.put("title", title);
            messageContent.put("content", content);
            messageContent.put("senderName", senderName);
            messageContent.put("senderId", senderId);
            messageContent.put("targetId", targetId);
            messageContent.put("targetType", targetType);
            messageContent.put("navigationPath", navigationPath);
            messageContent.put("navigationParams", navigationParams);
            messageContent.put("timestamp", System.currentTimeMillis());
            
            // 包装消息格式
            JSONObject wrappedMessage = new JSONObject();
            wrappedMessage.put("content", messageContent);
            wrappedMessage.put("read", false);
            wrappedMessage.put("timestamp", System.currentTimeMillis());
            
            // 存储到Redis
            String redisKey = "admin:unread:" + toUserId;
            redisTemplate.opsForList().rightPush(redisKey, wrappedMessage.toString());
            
            log.info("通知消息发送成功: toUserId={}, type={}", toUserId, notificationType);
            return R.ok("发送成功");
        } catch (Exception e) {
            log.error("发送通知消息失败", e);
            return R.fail("发送失败");
        }
    }
}